#!/usr/bin/groovy
@Library('test-shared-library') _

String getDockerImageVersion() {
    def versionLine = readFile("gradle.properties").split("\n").find() { line -> line.startsWith('dockerImageVersion') }
    return versionLine.split("=")[1]
}

Integer getNextDockerImageVersion(){
    getDockerImageVersion().toInteger() + 1
}

def withDocker(code) {
    def image = 'opsh2oai/sparkling_water_tests:' + getDockerImageVersion()
    retryWithDelay(3, 120, {
        withCredentials([usernamePassword(credentialsId: "harbor.h2o.ai", usernameVariable: 'REGISTRY_USERNAME', passwordVariable: 'REGISTRY_PASSWORD')]) {
            sh "docker login -u $REGISTRY_USERNAME -p $REGISTRY_PASSWORD harbor.h2o.ai"
            sh "docker pull harbor.h2o.ai/${image}"
        }
    })
    docker.image(image).inside("--init --privileged --dns 172.16.0.200") {
        sh "activate_java_8"
        code()
    }
}

node('docker && !mr-0xc8') {

    cleanWs()
    checkout scm
    def nextVersion = getNextDockerImageVersion()
    stage("Build Docker") {
        docker.withRegistry("http://harbor.h2o.ai") {
            withDocker {
                sh "./gradlew :sparkling-water-jenkins:createDockerFile"
            }
        }
        dir("jenkins/docker/regular-tests") {
            sh """
               cp -R ../conf conf
               docker pull harbor.h2o.ai/opsh2oai/h2o-3-hadoop-hdp-2.2:73
               docker build -t harbor.h2o.ai/opsh2oai/sparkling_water_tests:${nextVersion} -f Dockerfile .
               """
        }

    }

    stage("Publish Docker") {
        sh """
           docker push harbor.h2o.ai/opsh2oai/sparkling_water_tests:${nextVersion}
           """
    }
}
